"""This module provides mydouyn"""

import datetime
import json
import os
import platform
import random
import time

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from playwright.sync_api import Page, sync_playwright


########################################################################
class CMyCsdn:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """

    def __init__(
        self,
        cookies_path: str,
        login_url: str,
        upload_picture_url: str,
        upload_mp4_url: str,
    ):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        print("create CMyCsdn")

    def __del__(self):
        print("CMyCsdn is being destroyed")

    def auto_goods_weibo(self, habit_name: str, habit_detail: str):
        """
        upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            self.browser = playwright.chromium.launch(
                channel="chrome", headless=display_headless
            )
            login_page = self.login_or_restore_cookies()
            self.msg_goods_load(login_page, habit_name, habit_detail)
            self.browser.close()

    def login_or_restore_cookies(self) -> Page:
        """
        登录 context-->page
        """
        userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"

        context = self.browser.new_context(user_agent=userAgent)
        context.clear_cookies()
        page = context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("load cookies")
            # 从文件中加载 cookies
            with open(self.cookies_path, "r", encoding="utf-8") as f:
                cookies = json.load(f)
            context.add_cookies(cookies)
            time.sleep(3)
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(80)
            cookies = page.context.cookies()
            with open(self.cookies_path, "w", encoding="utf-8") as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page

    def msg_goods_load(self, page: Page, habit_name: str, habit_detail: str):
        """
        msg_up_load
        """
        page.goto(self.upload_picture_url)
        time.sleep(2)
        print(f"open  {self.upload_picture_url}")
        # 控制发文的次数
        begin = 4
        end = 100
        step = 5
        index = 0
        # 点击点赞100次
        for i in range(begin, end):
            try:
                for j in range(0, 10):
                    page.mouse.down()
                    page.mouse.down()
                    page.mouse.down()
                    page.wait_for_timeout(1000)
                num = random.randint(0, 10)
                page.wait_for_timeout(num * 1000)

                page.locator(
                    f"div:nth-child({i}) > .wbpro-scroller-item > .woo-panel-main > footer > div > div > div > div:nth-child(2) > div > .woo-box-flex"
                ).click()
                page.wait_for_timeout(500)
                print(f"打开评论 .... {i} done")
                data_time = datetime.datetime.now()
                formatted_time = data_time.strftime("%Y-%m-%d %H:%M:%S")
                temp = habit_detail + "\n" + formatted_time
                # <textarea placeholder="发布你的评论" class="Form_input_3JT2Q" ></textarea>
                # btn_msg = page.get_by_role("textbox", name="发布你的评论").last()

                # btn_msg = page.locator(
                #     "//textarea[@placeholder='发布你的评论' and contains(@class, 'Form_input_3JT2Q')]"
                # ).nth(i)
                btn_msg = page.locator("css=.Form_input_3JT2Q").nth(index)
                btn_msg.fill(temp)
                page.wait_for_timeout(5 * 1000)
                print(f"填写评论 .... {i} done")
                page.get_by_role("button", name="评论").nth(index).click()
                page.wait_for_timeout(5 * 1000)
                print(f"发布评论 .... {i} done")
                page.wait_for_timeout(5 * 1000)
                index += 1

            except Exception as myunkonw:
                print(f"发生异常：{myunkonw}")

            print(f"item {i} done")


def interface_auo_goods_weibo(habit_name, habit_detail):
    """
    对外调用接口
    """
    try:
        sys = platform.system()
        login_url = "https://weibo.com/newlogin"
        upload_picture_url = "https://weibo.com/"
        upload_mp4_url = "https://weibo.com/"
        if sys == "Windows":
            cookies_path = r"D:\mp4\etc\weibo_small.json"
        elif sys == "Darwin":
            cookies_path = r"/Users/wangchuanyi/mp4/etc/weibo_small.json"
        else:
            cookies_path = r"/root/bin/mycsdn_small.json"
        autoupload = CMyCsdn(
            cookies_path, login_url, upload_picture_url, upload_mp4_url
        )
        autoupload.auto_goods_weibo(habit_name, habit_detail)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")


###################################################
def interface_sell_goods_for_weibo():
    """
    每天写50字产品理解输出，10行代码
    """
    # 获取内容
    local_file_path = (
        r"/Users/wangchuanyi/money/years/p1_good_night/auto/good/weibo/config.txt"
    )
    sys = platform.system()
    if sys == "Windows":
        local_file_path = r"D:\p1_good_night\auto\good\weibo\config.txt"
    f = open(local_file_path, encoding="utf-8")
    artile_content = f.read()
    print(artile_content)
    f.close()

    artile_title = "学会销售自己的产品"

    try:
        interface_auo_goods_weibo(artile_title, artile_content)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")


if __name__ == "__main__":
    print("test")
    # playwright codegen https://blink.csdn.net/?spm=1010.2135.3001.5353
    # future_for_sleep()
    # job_defaults = {"coalesce": False, "max_instances": 1}
    interface_sell_goods_for_weibo()
    # # 调度器组件
    # backsched = BlockingScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    # # future_for_sleep callable函数 习惯养成--早睡早起
    # # crontab 是 Linux 系统中用于设置周期性被执行的指令的命令
    # # 0 0 * * *	每天的午夜（0 点）执行一次
    # backsched.add_job(future_for_sleep, CronTrigger.from_crontab("0 21 * * *"), id="get_up")
    # backsched.start()
